<!-- 产品碳足迹-模型搭建-输入输出表单-选择因子 -->

<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form :model="queryParam" layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Factor_name')">
                <a-input v-model="queryParam.name" allowClear :placeholder="$t('message.Please_enter')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Factor_denominator_unit')">
                <a-select v-model="queryParam.denominatorUnitId" allowClear :placeholder="$t('message.Please_select')" show-search
                          :filter-option="filterOption">
                  <a-select-option :value="item.id" v-for="(item, index) in fmData" :key="index">
                    {{ item.unitCode }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Applicable_scenario')">
                <a-input v-model="queryParam.scene" allowClear :placeholder="$t('message.Please_enter')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Applicable_industries')">
                <a-select v-model="queryParam.industryId" allowClear :placeholder="$t('message.Please_select')"
                          show-search :filter-option="filterOption">
                  <a-select-option :value="item.id" v-for="(item,index) in industryData" :key="index">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Release_country_organization')">
                <a-input v-model="queryParam.ownership" allowClear :placeholder="$t('message.Please_enter')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Release_organization')">
                <a-input v-model="queryParam.releaseOrg" allowClear :placeholder="$t('message.Please_enter')"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item label="">
                <a-button type="primary" @click="searchQuery">{{$t('message.Search')}}</a-button>
                <a-button style="margin-left: 8px" @click="searchReset">{{$t('message.Reset')}}</a-button>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 来源 -->
      <div class="laiyuan">{{$t('message.Source')}}：
        <a-checkbox-group v-model="checkedList" :options="plainOptions" @change="onChangePlainOptions"/>
      </div><!-- 我的收藏 -->
      <div class="cardBox">
        <a-table ref="table" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
                 :columns="columns" :dataSource="dataSource" :loading="loading" :pagination="ipagination"
                 :scroll="{ x: true }" :bordered="false" class="" rowKey="id" size="middle"
                 @change="handleTableChange">
          <div slot="factorValue" slot-scope="text, record">{{ (Number(record.factorValue)).toFixed(4) }}</div>
          <div slot="Unit" slot-scope="text, record">{{ record.numeratorUnit }}/{{ record.denominatorUnit }}</div>
          <div slot="type" slot-scope="text, record">
            <div v-if="record.type == 1">{{$t('message.Carbon_emission_factor_library')}}</div>
            <div v-if="record.type == 2">{{$t('message.Tissue_factor_library')}}</div>
          </div>
          <div class="m_cbFlex" style="padding: 0 5px;" slot="action" slot-scope="text, record">
            <a @click="onDetail(record)">{{$t('message.Detail')}}</a>
            <a-popconfirm :title="$t('message.collect')" :cancelText="$t('message.Cancel')" 
              :okText="$t('message.Confirm')" @confirm="() => onCollect(record)"
              v-if="record.collectStatus === '0' && record.type == 1"><a>{{$t('message.collect')}}</a>
            </a-popconfirm>
            <a-popconfirm :title="$t('message.Cancel_collect')" :cancelText="$t('message.Cancel')" 
              :okText="$t('message.Confirm')" @confirm="() => onCollect(record)"
              v-if="record.collectStatus === '1' && record.type == 1"><a>{{$t('message.Cancel_collect')}}</a>
            </a-popconfirm>
          </div>
        </a-table>
      </div>
    </a-card>
    <!-- 详情弹窗 -->
    <section class="m_popupBox" v-if="isShowDetailPopup">
      <tpyzDetail ref="tpyzDetail" @back="back"></tpyzDetail>
    </section>
  </div>
</template>

<script>
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {cloneObject} from "@/utils/util";
import {deleteAction, getAction, postAction} from "@api/manage";
import emptyBox from "@comp/common/emptyBox.vue";
import tpyzDetail from "@views/module_emission/tpfyzkView/modules/tpyzDetail.vue";
import {INDUSTRY} from "@/common/constKey";

export default {
  components: {
    emptyBox,
    tpyzDetail,
  },
  data() {
    return {
      selectedRowKeys: [],
      checkedList: [],
      plainOptions: [
        {label: this.$t('message.Carbon_emission_factor_library'), value: "1"},
        {label: this.$t('message.Tissue_factor_library'), value: "2"},
        {label: this.$t('message.my_collection'), value: "3"},
      ],
      // ======================================================
      loading: false,
      queryParam: {
        token: Vue.ls.get(ACCESS_TOKEN),
        emissionFactorOption: 0, // 碳排因子库
        privateFactorOption: 0, // 组织因子库
        myFactorOption: 0, // 我的收藏
        state: 1, // 发布状态
      },
      columns: [{
        title: this.$t('message.Factor_name'),
        align: "center",
        dataIndex: "name",
      }, {
        title: this.$t('message.Factor_value'),
        align: "center",
        dataIndex: "factorValue",
        scopedSlots: {customRender: 'factorValue'},
      }, {
        title: this.$t('message.Unit'),
        align: "center",
        scopedSlots: {customRender: "Unit"},
      }, {
        title: this.$t('message.Specifications_and_models'),
        align: "center",
        dataIndex: "model",
      }, {
        title: this.$t('message.Applicable_scenario'),
        align: "center",
        dataIndex: "scene",
      }, {
        title: this.$t('message.Applicable_industries'),
        align: "center",
        dataIndex: "industry",
      }, {
        title: this.$t('message.Release_organization'),
        align: "center",
        dataIndex: "releaseOrg",
      }, {
        title: this.$t('message.Release_year'),
        align: "center",
        dataIndex: "releaseYear",
        // defaultSortOrder: 'descend',
        sorter: (a, b) => a.releaseYear - b.releaseYear,
      }, {
        title: this.$t('message.Release_country_organization'),
        align: "center",
        dataIndex: "ownership",
      }, {
        title: this.$t('message.Database'),
        align: "center",
        dataIndex: "type",
        scopedSlots: {customRender: "type"},
      }, {
        title: this.$t('message.Handle'),
        dataIndex: "action",
        align: "center",
        fixed: "right",
        width: 140,
        scopedSlots: {customRender: "action"},
      }],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ["10", "20", "30"],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      // ======================================================
      dataSource: [], // 表格数据
      isShowDetailPopup: false, // 详情弹窗
      fmData: [], // 分母选项数据
      industryData: [], // 行业数据
    };
  },
  created() {
    this.getData(1);
    this.getOption()
  },
  methods: {
    /**
     * 收藏碳排因子
     */
    onCollect(item) {
      if (item.collectStatus === "1") {
        // 取消收藏
        deleteAction("/CyEmissionFactorCollect/cyEmissionFactorCollect/delete", {
          id: item.id,
        }).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('message.delete_collect_success'))
            this.getData(1)
          }
        });
      } else if (item.collectStatus === "0") {
        // 收藏
        getAction("/CyEmissionFactorCollect/cyEmissionFactorCollect/add", {
          id: item.id,
        }).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('message.collect_success'))
            this.getData(1)
          }
        });
      }
    },
    /**
     * 表格选择因子
     * @param selectedRowKeys
     * @param selectedRows
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      console.log('onSelectChange',selectedRowKeys,selectedRows);
      if (selectedRowKeys.length == 1 || selectedRowKeys.length < 1) {
        this.selectedRowKeys = selectedRowKeys;
        this.$emit("onselectedRows", selectedRows[0]);
      }
    },
    /**
     * 来源筛选
     * @param e
     */
    onChangePlainOptions(e) {
      console.log(e);
      console.log(this.checkedList);
      if (this.checkedList.indexOf("1") != -1) {
        this.queryParam.emissionFactorOption = 1;
      } else {
        this.queryParam.emissionFactorOption = 0;
      }
      if (this.checkedList.indexOf("2") != -1) {
        this.queryParam.privateFactorOption = 1;
      } else {
        this.queryParam.privateFactorOption = 0;
      }
      if (this.checkedList.indexOf("3") != -1) {
        this.queryParam.myFactorOption = 1;
      } else {
        this.queryParam.myFactorOption = 0;
      }
      this.getData(1);
    },
    /**
     * 详情
     */
    onDetail(item) {
      console.log('onDetail', item);
      this.isShowDetailPopup = true;
      this.$nextTick(() => {
        console.log("onDetail", this.$refs);
        this.$refs.tpyzDetail.detailIndex = 0;
        this.$refs.tpyzDetail.detailKeys = [item.id];
        this.$refs.tpyzDetail.getData();
      });
    },
    /**
     * 查询
     */
    searchQuery() {
      console.log("searchQuery");
      this.getData(1);
    },
    /**
     * 重置
     */
    searchReset() {
      console.log("searchReset");
      this.queryParam = {
        token: Vue.ls.get(ACCESS_TOKEN),
        emissionFactorOption: 0, // 碳排因子库
        privateFactorOption: 0, // 组织因子库
        myFactorOption: 0, // 我的收藏
      }
      this.checkedList = []
      this.getData(1);
    },
    /**
     * 表格分页
     * @param pagination
     */
    handleTableChange(pagination) {
      console.log(pagination);
      this.ipagination = pagination;
      this.getData();
    },
    getData(page) {
      // 表格数据
      if (page === 1) {
        this.ipagination.current = 1;
      }
      this.loading = true
      let reqData = cloneObject(this.queryParam)
      reqData.pageNo = this.ipagination.current
      reqData.pageSize = this.ipagination.pageSize
      getAction("/footprintProduct/cyFootprintProduct/privateList", reqData).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records || [];
          this.ipagination.total = res.result.total
        }
      }).finally(() => {
        this.loading = false
      });
    },
    getOption() {
      // 行业
      getAction("/sys/category/childList", {
        pid: INDUSTRY,
      }).then((res) => {
        if (res.success) {
          this.industryData = res.result || [];
        }
      });
      // 因子分母单位
      getAction("/emission/factor/cyEmissionUnit/getAllUnit").then((res) => {
        if (res.success) {
          this.fmData = res.result || [];
        }
      });
    },
    // ==================================================================
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0);
    },
    back() {
      this.isShowDetailPopup = false;
      this.getData(1);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  background: #f5f8f7;
  padding: 0;
}

/deep/ .table-page-search-wrapper {
  padding: 24px 24px 4px;
  background: #F3F3F3;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-form-item {
  margin-bottom: 20px !important;
}

.laiyuan {
  padding: 24px 0 16px 0;
  display: flex;
  justify-content: end;
  background: #ffffff;
}

.cardBox {
  background: #ffffff;
  border-radius: 3px;
}

</style>
